package com.party.notify.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.utils.HttpUtils;
import com.party.core.model.notify.Instance;
import com.party.core.model.notify.InstanceConstant;
import com.party.core.model.notify.InstanceWay;
import com.party.core.model.system.TargetType;
import com.party.core.service.member.IPackageCountService;
import com.party.core.service.notify.IInstanceService;
import com.party.notify.jms.publisher.service.INotifyPublisherService;
import com.party.notify.sms.model.SmsMessage;
import com.party.notify.sms.service.ISmsService;
import com.party.notify.template.service.ITemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短信发送接口
 * User: wei.li
 * Date: 2017/4/5
 * Time: 22:52
 */

@Service
public class SmsService implements ISmsService {

    @Autowired
    private ITemplateService templateService;

    @Autowired
    private INotifyPublisherService notifyPublisherService;

    @Autowired
    private IInstanceService instanceService;

    @Autowired
    private IPackageCountService packageCountService;


    // 短信发送网关地址
    @Value("#{sms['sms.url']}")
    private String url;

    // 短信发送账户
    @Value("#{sms['sms.uid']}")
    private String uid;

    // 短信发送密码
    @Value("#{sms['sms.pwd']}")
    private String pwd;

    //公众号编号
    @Value("${sms.timeout}")
    private Integer timeout;

    protected static Logger logger = LoggerFactory.getLogger(SmsService.class);


    /**
     * 短信推送
     * @param template 模板
     * @param isWrite 是否写入
     * @param authorId 发送者
     * @param templateId 模板编号
     * @param telephone 手机号
     * @param content 内容
     */
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public void push(boolean isWrite,String authorId, String template, String templateId, String telephone, HashMap<String, Object> content) {
        // 根据事项找到模板
        String massage = templateService.replace(template, content);

        //添加签名
        String partnerName = (String)content.get("{partner}");
        massage = templateService.smsSign(massage, partnerName);
        SmsMessage smsMessage = new SmsMessage();
        smsMessage.setContent(massage);
        smsMessage.setTelephone(telephone);
        smsMessage.setMemberId((String) content.get("senderId"));
        smsMessage.setTargetId((String) content.get("targetId"));
        smsMessage.setWay((String) content.get("way"));
        smsMessage.setTemplateId(templateId);
        smsMessage.setIsNewFlag((Integer) content.get(InstanceConstant.IS_NEW_FLAG));
        smsMessage.setIsPermitFlag((Integer) content.get(InstanceConstant.IS_PERMIT_FLAG));

        //短信写入
        String id = this.write(smsMessage);
        smsMessage.setId(id);

        try {
            if (Instance.FLAG_YES.equals(smsMessage.getIsNewFlag())) {
                packageCountService.updateUseCount(smsMessage.getMemberId(), TargetType.PUSH_SMS.getCode());
            }
        } catch (Exception e) {
            logger.error("更新短信使用情况异常——合作商id：" + smsMessage.getMemberId(), e);
        }

        try {
            logger.info("短信发送——————开始入队列——————smsMessage：：："+ JSONObject.toJSONString(smsMessage));
            notifyPublisherService.send(smsMessage, Constant.MESSAGE_CHANNEL_SMS, isWrite);
        } catch (Exception e) {
            logger.error("短信发送异常{}", e);
        }
    }

    /**
     * 短信推送
     * @param telephone 手机号
     * @param content 内容
     */
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public void push(String telephone, String content){
        SmsMessage smsMessage = new SmsMessage();
        smsMessage.setContent(content);
        smsMessage.setTelephone(telephone);
        String id = this.write(smsMessage);
        smsMessage.setId(id);
        try {
            notifyPublisherService.send(smsMessage, Constant.MESSAGE_CHANNEL_SMS, true);
        } catch (Exception e) {
            logger.error("短信发送异常{}", e);
        }
    }

    /**
     * 写入消息
     * @param smsMessage 短信内容
     */
    public String write(SmsMessage smsMessage) {
        // 根据事项找到模板
        String way = null == smsMessage.getWay() ? InstanceWay.SYSTEM.getName() : smsMessage.getWay();
        Instance instance = new Instance();
        instance.setTitle(smsMessage.getContent());
        instance.setChannelType(Constant.MESSAGE_CHANNEL_SMS);
        instance.setReceiver(smsMessage.getTelephone());
        instance.setMemberId(smsMessage.getMemberId());
        instance.setWay(way);
        instance.setTemplateId(smsMessage.getTemplateId());
        instance.setTargetId(smsMessage.getTargetId());
        instance.setTime(1);
        instance.setIsNewFlag(smsMessage.getIsNewFlag());
        instanceService.insert(instance);
        return instance.getId();
    }

    /**
     * 发送短信
     * @param isWrite 是否写入
     * @param smsMessage 内容
     * @return 发送结果
     */
    public boolean send(boolean isWrite, SmsMessage smsMessage) {
        String result = send(smsMessage.getTelephone(), smsMessage.getContent());
        Instance instance = instanceService.get(smsMessage.getId());
        Integer isSuccess =  Constant.IS_FAIL;
        if (result.startsWith("0")){
            isSuccess = Constant.IS_SUCCESS;
            List<String> results = Lists.newArrayList(Splitter.on("\n").split(result));
            instance.setMsgId(results.get(1));
            result = "0";
        }

        // 提交结果, msgid
        instance.setIsSuccess(isSuccess);
        instance.setResult(result);
        instance.setUpdateDate(new Date());
        instanceService.update(instance);
        return true;
    }


    /**
     * 短信发送
     * @param tel 手机号
     * @param content 内容
     */
    public String send(String tel, String content){
        return send(tel, content, uid, pwd, url);
    }

    /**
     * 短信发送
     * @param tel 手机号
     * @param content 内容
     * @param uid 账号
     * @param pwd 密码
     * @param url 连接
     * @return
     */
    public String send(String tel, String content, String uid, String pwd, String url) {
        try {
            Map<String, String> parm = Maps.newHashMap();
            parm.put("account", uid);
            parm.put("pswd", pwd);
            parm.put("mobile", tel);
            parm.put("msg",URLEncoder.encode(content, "utf-8"));
            parm.put("needstatus", "true");

            logger.info("短信发送请求参数：content--{}", content);

            String msg = HttpUtils.httpPost(url, parm);

            String str=msg.split(",")[1];
            logger.info("短信发送返回报文{}", str);

            return str;
        } catch (Exception e) {
            logger.error("短信发送异常",e);
        }
        return "";
    }
}
